<?php

use GuzzleHttp\Client;

class Lib_Request_Http
{

    private static $obj = null;


    private function __construct()
    {
    }

    /**
     * 获取单例
     * @param string $hl
     * @param number $timeout
     * @return Lib_Request_Http
     */
    public static function getInstance()
    {
        if (is_null(self::$obj)) {
            self::$obj = new self();
        }

        return self::$obj;
    }

    /**
     * @desc  curl 请求
     * @param $url
     * @param $data
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function https_request($url, $data)
    {
        try {
            $client = new GuzzleHttp\Client();
            $response = $client->request('POST', $url, [
                'form_params' => $data
            ]);

        } catch (ClientException $e) {
            Func_Log::write("https_request", 'getRequest', var_export($e->getRequest(), true));
            Func_Log::write("https_request", 'getResponse', var_export($e->getResponse(), true));
        }

        return $response->getBody()->getContents();
    }

    /**
     * @curl 上传文件
     * @param $url
     * @param $data ($path  '/path/to/file)
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function https_request_file($url, $data)
    {
        try {
            $client = new GuzzleHttp\Client();
            $response = $client->request('POST', $url, [
                'multipart' => [
                    [
                        'name' => 'file',
                        'contents' => fopen($data['file'], 'r'),
                    ],
                    [
                        'name' => 'isView',
                        'contents' => isset($data['isView']) ? $data['isView'] : 'NOVIEW'
                    ],
                    [
                        'name' => 'fileName',
                        'contents' => isset($data['fileName']) ? $data['fileName'] : ''
                    ],
                ],
            ]);

        } catch (ClientException $e) {
            Func_Log::write("https_request_file", 'getRequest', var_export($e->getRequest(), true));
            Func_Log::write("https_request_file", 'getResponse', var_export($e->getResponse(), true));
        }
        return $response->getBody()->getContents();
    }


}
